package com.lancoo.klgcourseware.ui.activity;

import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.Html;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.lancoo.klgcourseware.R;
import com.lancoo.klgcourseware.base.BaseKlgActivity;
import com.lancoo.klgcourseware.entity.bean.KlgCommonBean;
import com.lancoo.klgcourseware.entity.bean.KlgDbConstant;
import com.lancoo.klgcourseware.manager.KlgLocalMediaManager;
import com.lancoo.klgcourseware.manager.KlgMediaManager;
import com.lancoo.klgcourseware.ui.widget.VolumeAlignImageSpan;
import com.lancoo.klgcourseware.utils.KlgBitmapUtils;
import com.lancoo.klgcourseware.utils.KlgToolUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by pengmi on 2019/8/27 10:22
 * Description:结果展示界面基类
 */
public abstract class KlgResulstBaseAcitivy extends BaseKlgActivity {

    public static final String KEY_KLGCOMMONBEN="klgCommonBean";
    public static final String KEY_TRAINSCORE="trainScore";
    public static final String KEY_TRAINTIME="trainTime";
    public static final String KEY_TRAINRECORDER="trainRecorder";

    protected int score,studyTime;//训练得分，训练时长
    protected KlgCommonBean klgCommonBean;
    protected ImageView img_usPhonetic,img_unPhonetic,img_senPhonetic,img_myRecord;
    private KlgMediaManager klgMediaManager;
    private KlgLocalMediaManager resultMediaManager;
    private VolumeAlignImageSpan centerAlignImageSpan;
    private TextView tv_sentenceStructures;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        klgCommonBean = (KlgCommonBean) getIntent().getSerializableExtra(KEY_KLGCOMMONBEN);
        score=getIntent().getIntExtra(KEY_TRAINSCORE,0);
        studyTime=getIntent().getIntExtra(KEY_TRAINTIME,0);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(klgMediaManager!=null){
            klgMediaManager.pause();
        }
        if(resultMediaManager!=null){
            resultMediaManager.pause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(klgMediaManager!=null){
            klgMediaManager.release();
            klgMediaManager=null;
        }
        if(resultMediaManager!=null){
            resultMediaManager.release();
            resultMediaManager=null;
        }
        if(centerAlignImageSpan!=null&&tv_sentenceStructures!=null){
            centerAlignImageSpan.destoryVolumeImageSpan(tv_sentenceStructures);
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int id=v.getId();
        if(id==R.id.ll_sentence_structures){//例句
            String url = (String) v.getTag();
            playSound(url,img_senPhonetic);
        }else if(id==R.id.ll_us_phonetic){//美式
            String url = (String) v.getTag();
            playSound(url,img_usPhonetic);
        }else if(id==R.id.ll_un_phonetic){//英式
            String url = (String) v.getTag();
            playSound(url,img_unPhonetic);
        }else if(id==R.id.img_picture){
            String url = KlgDbConstant.mediaUrl+klgCommonBean.getClassicSen();
            List<String> urlList=new ArrayList<>();
            urlList.add(url);
            KlgImageViewPagerActivity.launch(this,(ImageView) v,urlList,0);
        }
    }

    protected void initWordMsg(){
        if(klgCommonBean==null){
            return;
        }
        //知识点名称
        TextView tv_klgName = findViewById(R.id.tv_klg_name);
        tv_klgName.setText(klgCommonBean.getKlgName());
        //知识点释义
        if(TextUtils.isEmpty(klgCommonBean.getExplain())){
            findViewById(R.id.tv_meaning_explain).setVisibility(View.GONE);
            findViewById(R.id.tv_meaning).setVisibility(View.GONE);
        }else {
            TextView tv_explain=findViewById(R.id.tv_meaning);
            tv_explain.setText(klgCommonBean.getExplain());
            TextView tv_explainTitle = findViewById(R.id.tv_meaning_explain);
            tv_explainTitle.setText(R.string.klg_meaning_plu);

        }
        //句型
        if(TextUtils.isEmpty(klgCommonBean.getParaphrase())){
            findViewById(R.id.tv_sentence_pattern_explain).setVisibility(View.GONE);
            findViewById(R.id.tv_sentence_pattern).setVisibility(View.GONE);
        }else{
            TextView tv_sentence = findViewById(R.id.tv_sentence_pattern);
            tv_sentence.setText(klgCommonBean.getParaphrase());
            TextView tv_sentenceTitle = findViewById(R.id.tv_sentence_pattern_explain);
            tv_sentenceTitle.setText(R.string.klg_sentence_pattern_plu);
        }
        //用法
        if(TextUtils.isEmpty(klgCommonBean.getUsage())){
            findViewById(R.id.tv_usage_analysis_explain).setVisibility(View.GONE);
            findViewById(R.id.tv_usage_analysis).setVisibility(View.GONE);
        }else{
            TextView tv_usageAnalysis = findViewById(R.id.tv_usage_analysis);
            tv_usageAnalysis.setText(Html.fromHtml(klgCommonBean.getUsage()));
            TextView tv_usageTitle = findViewById(R.id.tv_usage_analysis_explain);
            tv_usageTitle.setText(R.string.klg_usage_analysis_plu);
        }
        //例句
        if(TextUtils.isEmpty(klgCommonBean.getClassicSen())){
            findViewById(R.id.tv_sentence_structures_explain).setVisibility(View.GONE);
            findViewById(R.id.ll_sentence_structures).setVisibility(View.GONE);
        }else{
            if(TextUtils.equals("ESP",klgCommonBean.getKlgType())){
                findViewById(R.id.tv_sentence_structures_explain).setVisibility(View.GONE);
                findViewById(R.id.ll_sentence_structures).setVisibility(View.GONE);
                ViewStub stub = findViewById(R.id.viewstub_train_picture);
                if(stub!=null){
                    stub.inflate();
                    final ImageView img_picture=findViewById(R.id.img_picture);
//                    Glide.with(getContext()).load(KlgDbConstant.mediaUrl+klgCommonBean.getClassicSen()).into(img_picture);
                    Glide.with(this).asBitmap().load(KlgDbConstant.mediaUrl+klgCommonBean.getClassicSen())
                            .into(new SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL,Target.SIZE_ORIGINAL) {
                                @Override
                                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                    if(isFinishing()){
                                        return;

                                    }
                                    int width = resource.getWidth();//图片原始宽度
                                    int height = resource.getHeight();//图片原始高度
                                    int scaledW = KlgToolUtils.getWidthInPx(KlgResulstBaseAcitivy.this)-KlgToolUtils.dip2px(KlgResulstBaseAcitivy.this,KlgToolUtils.isPad(KlgResulstBaseAcitivy.this)?120f:70f);//固定图片展示高度为180dp
                                    int scaledH = (height * scaledW) /width ;//计算出按比缩放后的宽度
//                                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(scaledW, scaledH);
//                                    img_picture.setLayoutParams(lp);
                                    String format =klgCommonBean.getClassicSen().substring(klgCommonBean.getClassicSen().lastIndexOf(".")+1);
                                    if(TextUtils.equals(format.toLowerCase(),"png")){
                                        img_picture.setImageBitmap(Bitmap.createScaledBitmap(resource, scaledW, scaledH, true));
                                    }else{
                                        img_picture.setImageBitmap(KlgBitmapUtils.zoomImage(resource,scaledW,scaledH));
                                    }

                                }
                            });
                    img_picture.setOnClickListener(this);
                }
            }else{
                tv_sentenceStructures = findViewById(R.id.tv_sentence_structures);
                TextView tv_sentenceStructureChinese = findViewById(R.id.tv_sentence_structures_chinese);
//            tv_sentenceStructures.setText(Html.fromHtml(klgCommonBean.getClassicSen()));
                tv_sentenceStructureChinese.setText(klgCommonBean.getClassicTrain());
                SpannableStringBuilder spannableStringBuilder=new SpannableStringBuilder();
                SpannableString ss_content=new SpannableString(Html.fromHtml(klgCommonBean.getClassicSen().replace("font color='#0077f0'","font color='#64a9d0'")));
                spannableStringBuilder.append(ss_content);
                if(!TextUtils.isEmpty(klgCommonBean.getClassicVoice())){
                    findViewById(R.id.ll_sentence_structures).setTag(klgCommonBean.getClassicVoice());
                    findViewById(R.id.ll_sentence_structures).setOnClickListener(this);
                    String imgSpanStr="  lpl";
                    SpannableString ss_volume=new SpannableString(imgSpanStr);
                    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.klg_volume_cyan_4);
                    if(centerAlignImageSpan==null){
                        centerAlignImageSpan = new VolumeAlignImageSpan(this,bitmap);
                    }else{
                        centerAlignImageSpan.destoryVolumeImageSpan(tv_sentenceStructures);
                    }
                    ss_volume.setSpan(centerAlignImageSpan,imgSpanStr.length()-3,imgSpanStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannableStringBuilder.append(ss_volume);
//                    SpannableString ss_end=new SpannableString("1");
//                    ss_end.setSpan(new ForegroundColorSpan(Color.TRANSPARENT),0,1,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//                    spannableStringBuilder.append(ss_end);
                }
                tv_sentenceStructures.setText(spannableStringBuilder);
                TextView tv_sentenceTitle = findViewById(R.id.tv_sentence_structures_explain);
                tv_sentenceTitle.setText(R.string.klg_sentence_structures_plu);
            }


        }
        //知识点发音
        if(TextUtils.isEmpty(klgCommonBean.getUn_phonetic())&&TextUtils.isEmpty(klgCommonBean.getUs_phonetic())&&TextUtils.isEmpty(klgCommonBean.getUn_voice())&&TextUtils.isEmpty(klgCommonBean.getUs_voice())){
//            findViewById(R.id.ll_fayin).setVisibility(View.GONE);
        }else{
            ViewStub viewStub = findViewById(R.id.viewstub_phonetic);
            if(viewStub!=null){
                viewStub.inflate();
            }
            TextView tv_phonetic = findViewById(R.id.tv_phonetic);
            tv_phonetic.setText(R.string.klg_phonetic_plu);
            if(TextUtils.isEmpty(klgCommonBean.getUn_phonetic())&&TextUtils.isEmpty(klgCommonBean.getUn_voice())){
                findViewById(R.id.ll_un_phonetic).setVisibility(View.GONE);
            }else{
                TextView tv_unPhonetic = findViewById(R.id.tv_un_phonetic);
                if(TextUtils.isEmpty(klgCommonBean.getUn_phonetic())){
                    tv_unPhonetic.setText(getString(R.string.klg_un));
                }else{
                    tv_unPhonetic.setText(getString(R.string.klg_un)+" "+ klgCommonBean.getUn_phonetic());
                }
                if(!TextUtils.isEmpty(klgCommonBean.getUn_voice())){
                    findViewById(R.id.ll_un_phonetic).setTag(klgCommonBean.getUn_voice());
                    findViewById(R.id.ll_un_phonetic).setOnClickListener(this);
                }
                try{
                    Typeface typeFace = Typeface.createFromAsset(getAssets(), "klg_droid_sans_bold.ttf");
                    tv_unPhonetic.setTypeface(typeFace);
                }catch (Exception e){

                }
            }
            if(TextUtils.isEmpty(klgCommonBean.getUs_phonetic())&&TextUtils.isEmpty(klgCommonBean.getUs_voice())){
                findViewById(R.id.ll_us_phonetic).setVisibility(View.GONE);
            }else{
                TextView tv_usPhonetic =findViewById(R.id.tv_us_phonetic);
                if(TextUtils.isEmpty(klgCommonBean.getUs_phonetic())){
                    tv_usPhonetic.setText(getString(R.string.klg_us));
//                      findViewById(R.id.tv_us_phonetic).setVisibility(View.GONE);
                }else{
                    tv_usPhonetic.setText(getString(R.string.klg_us)+" "+ klgCommonBean.getUs_phonetic());
                }
                if(!TextUtils.isEmpty(klgCommonBean.getUs_voice())){
                    findViewById(R.id.ll_us_phonetic).setTag(klgCommonBean.getUs_voice());
                    findViewById(R.id.ll_us_phonetic).setOnClickListener(this);
                }
                try{
                    Typeface typeFace = Typeface.createFromAsset(getAssets(), "klg_droid_sans_bold.ttf");
                    tv_usPhonetic.setTypeface(typeFace);
                }catch (Exception e){

                }
            }
        }
        setWordMsgStyleMargin(findViewById(R.id.tv_phonetic));
        setWordMsgStyleMargin(findViewById(R.id.tv_meaning_explain));
        setWordMsgStyleMargin(findViewById(R.id.tv_sentence_pattern_explain));
        setWordMsgStyleMargin(findViewById(R.id.tv_usage_analysis_explain));
        setWordMsgStyleMargin(findViewById(R.id.tv_sentence_structures_explain));
        setWordMsgStyleMargin(findViewById(R.id.tv_picture_explain));
        //音频播放动画
        img_usPhonetic = findViewById(R.id.img_us_phonetic);
        img_unPhonetic = findViewById(R.id.img_un_phonetic);
        img_senPhonetic = findViewById(R.id.img_sentence_strutures);
        img_senPhonetic.setVisibility(View.GONE);

    }



    private void setWordMsgStyleMargin(View view){
        if(view==null){
            return;
        }
        int marginTop= KlgToolUtils.dip2px(this,17);
        int marginBottom=KlgToolUtils.dip2px(this,10);
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view.getLayoutParams();
        layoutParams.topMargin=marginTop;
        layoutParams.bottomMargin=marginBottom;
        view.setLayoutParams(layoutParams);
    }

    /**
     * 开启音频播放
     * @param url 音频url
     * @param img imgView
     */
    protected void playSound(final String url, final ImageView img){
        updateCountTimeStyle(true);
        if(klgMediaManager==null){
            klgMediaManager = new KlgMediaManager(this);
        }
        if(resultMediaManager!=null){
            resultMediaManager.pause();
        }
        controlImgAnimation(false,false,false,false);
        klgMediaManager.setUpMedia(url, new KlgMediaManager.OnPlayListener() {

            @Override
            public void onComplete() {
                if(img==img_myRecord){
                    myRecordPlayComplete();
                }else{
                    controlImgAnimation(false,false,false,false);
                }

            }

            @Override
            public void onStartError() {
                controlImgAnimation(false,false,false,false);
            }

            @Override
            public void onPausePlay() {

            }

            @Override
            public void onSourceError() {
                controlImgAnimation(false,false,false,false);
            }

            @Override
            public void onResumePlay() {

            }

            @Override
            public void onStopPlay() {

            }

            @Override
            public void onPrepare() {
                if(klgMediaManager!=null){
                    klgMediaManager.start();
                }
                controlImgAnimation(img==img_usPhonetic,img==img_unPhonetic,img==img_senPhonetic,img==img_myRecord);
            }

            @Override
            public void onBufferingUpdate(MediaPlayer mp, int percent) {

            }
        });
    }

    /**
     * 设置动画
     * @param img
     * @param isAnimation
     */
    protected void volumeAnimationControl(ImageView img, boolean isAnimation){
        if(img!=null&&img.getVisibility()== View.VISIBLE){
            if(isAnimation){
//                img.setImageResource(R.drawable.lgklg_animation_list_volume_cyan);
                img.setBackground(null);
                ((AnimationDrawable)img.getDrawable()).start();
            }else{
//                img.setImageResource(R.drawable.lgklg_volume_cyan_3);
                img.setBackgroundResource(R.drawable.klg_volume_cyan_3);
                ((AnimationDrawable)img.getDrawable()).stop();
                ((AnimationDrawable)img.getDrawable()).selectDrawable(0);

            }
        }
    }

    /**
     * 控制美式，英式，例句播放动画
     */
    protected void controlImgAnimation(boolean isOpend,boolean isOpen1,boolean isOpend2,boolean isOpend3){
        volumeAnimationControl(img_usPhonetic,isOpend);
        volumeAnimationControl(img_unPhonetic,isOpen1);
        volumeAnimationControl(img_senPhonetic,isOpend2);
        volumeAnimationControl(img_myRecord,isOpend3);
        if(centerAlignImageSpan==null){
            return;
        }
        if(isOpend2){
            centerAlignImageSpan.startVolumeAnimation(tv_sentenceStructures);
        }else{
            centerAlignImageSpan.stopVolumeAnimation(tv_sentenceStructures);
        }
    }

    /**
     *  初始化滴水音频
     */
    protected void initDripSound(boolean isPassd){
        if(resultMediaManager==null){
            resultMediaManager = new KlgLocalMediaManager();
            try {
                String music=isPassd?"klg_keep_trying.mp3":"klg_result_congratulations.mp3";
                AssetFileDescriptor assetFileDescriptor = getAssets().openFd(music);
                resultMediaManager.setUpMedia(assetFileDescriptor, new KlgLocalMediaManager.OnPlayListener() {
                    @Override
                    public void onComplete() {

                    }

                    @Override
                    public void onStartError() {

                    }

                    @Override
                    public void onPausePlay() {

                    }

                    @Override
                    public void onSourceError() {

                    }

                    @Override
                    public void onResumePlay() {

                    }

                    @Override
                    public void onStopPlay() {

                    }

                    @Override
                    public void onPrepare() {
                        resultMediaManager.start();
                    }

                    @Override
                    public void onBufferingUpdate(MediaPlayer mp, int percent) {

                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    protected void updateCountTimeStyle(boolean isCloseCountTime){}

    protected void myRecordPlayComplete(){}
}
